package com.isljj.web_chat2.config;

import com.isljj.web_chat2.constant.Constant;
import com.isljj.web_chat2.model.User;
import com.isljj.web_chat2.utils.CookieUtils;
import com.isljj.web_chat2.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

//拦截器
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private JWTUtils jwtUtils;
    private CookieUtils cookieUtils;
    LoginInterceptor(JWTUtils jwtUtils,CookieUtils cookieUtils){
        this.jwtUtils = jwtUtils;
        this.cookieUtils = cookieUtils;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String JwtToken = request.getHeader(Constant.REQUEST_TOKEN_KEY);
        //System.out.println(JwtToken);

        if(JwtToken==null){
            String cookie = (request.getHeader("cookie"));
            if(cookie==null) {
                //log.info("拦截器 -  cookie等于空" );
                response.setStatus(401);
                response.sendRedirect("/login.html");
                return false;
            }
            log.info("cookie - " + cookie);
            JwtToken= cookieUtils.parseToken(cookie);
            if(JwtToken==null) {
                //log.info("拦截器 -  JwtToken等于空" );
                response.setStatus(401);
                response.sendRedirect("/login.html");
                return false;
            }
        }
        User user = jwtUtils.getUserByToken(JwtToken);
        //log.info(user.toString());
        if(user!=null){
            return true;
        }else {
            //log.info("拦截器 -  user等于空" );
            response.setStatus(401);
            response.sendRedirect("/login.html");
            return false;
        }
    }
}
